Locators with Java in Selenium
Locators are one of the most important concepts in Selenium WebDriver. A locator is a mechanism used to identify and locate a specific web element on a web page, such as a text box, button, link, checkbox, radio button, dropdown, image, or any other HTML element.
In Selenium with Java, locators are used with the WebDriver and WebElement APIs to find elements and perform actions such as click, type, clear, select, read text, and verify attributes.
For example, when Selenium needs to enter a username into a login form, it first has to identify the username field. A locator tells Selenium exactly which HTML element it should interact with.
Course Resource: Selenium Training | Register for Course Demo
1. What is a Locator?
A locator is a technique used by Selenium WebDriver to identify an HTML element within a web page.
Every web page contains HTML elements. These elements may have attributes such as id, name, class, href, value, type, and other attributes. Selenium uses these attributes and expressions to locate elements.
WebElement username = driver.findElement(By.id("username"));
In this example:
- driver is the WebDriver object.
- findElement() searches for an element.
- By.id() specifies the locator strategy.
- username is the WebElement variable.
2. Why are Locators Important?
Locators are the foundation of Selenium automation. Selenium cannot interact with a web element until it knows which element to target.
- Identify text boxes.
- Locate buttons.
- Find links.
- Locate checkboxes and radio buttons.
- Select dropdown elements.
- Read information from web pages.
- Perform actions on dynamic web pages.
- Build reusable automation scripts.
- Automate complete business workflows.
3. Basic Selenium Locator Syntax
The most common syntax for locating an element in Selenium with Java is:
driver.findElement(By.locatorStrategy("locatorValue"));
Example:
driver.findElement(By.id("username"));
To store the element in a variable:
WebElement username = driver.findElement(By.id("username"));
4. Selenium Locator Strategies
Selenium provides eight commonly used locator strategies for identifying elements.
| Locator | Java Syntax | Common Usage |
| ID | By.id() | Locate using the id attribute |
| Name | By.name() | Locate using the name attribute |
| Class Name | By.className() | Locate using a class attribute |
| Tag Name | By.tagName() | Locate using an HTML tag |
| Link Text | By.linkText() | Locate a link using complete visible text |
| Partial Link Text | By.partialLinkText() | Locate a link using part of its visible text |
| CSS Selector | By.cssSelector() | Locate using CSS selector syntax |
| XPath | By.xpath() | Locate using XPath expressions |
5. ID Locator
The ID locator identifies an element using its HTML id attribute.
HTML:
<input type="text" id="username">
Java:
WebElement username = driver.findElement(By.id("username"));
ID is usually a simple locator strategy when the ID is unique and stable.
Example
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Password123");
Advantages of ID Locator
- Simple syntax.
- Easy to understand.
- Usually direct and readable.
- Useful when the ID is unique and stable.
Problem with Dynamic IDs
Some applications generate IDs dynamically.
<input id="user_827364" type="text">
If the numeric portion changes every time the page loads, directly using that ID may make the automation script unstable.
6. Name Locator
The Name locator identifies an element using the HTML name attribute.
HTML:
<input type="text" name="username">
Java:
WebElement username = driver.findElement(By.name("username"));
Example
driver.findElement(By.name("email")).sendKeys("[email protected]");
7. Class Name Locator
The Class Name locator identifies an element using its class attribute.
HTML:
<button class="login-button">Login</button>
Java:
driver.findElement(By.className("login-button")).click();
When using By.className(), provide a single class name rather than a compound class string containing spaces.
Example of Multiple Classes
<button class="btn primary login-button">Login</button>
Do not use:
By.className("btn primary login-button");
Instead, use one class if it uniquely identifies the element:
By.className("login-button");
Alternatively, use a CSS selector:
By.cssSelector("button.btn.primary.login-button");
8. Tag Name Locator
The Tag Name locator identifies elements based on their HTML tag.
Examples of HTML tags include:
- input
- button
- a
- div
- table
- tr
- td
- h1
- p
List<WebElement> links = driver.findElements(By.tagName("a"));
Tag Name is especially useful when you want to retrieve multiple elements of the same type.
9. Link Text Locator
Link Text locates an anchor element using its complete visible text.
HTML:
<a href="/login">Login</a>
Java:
driver.findElement(By.linkText("Login")).click();
Another Example
driver.findElement(By.linkText("Forgot Password?")).click();
The visible text must match the link text used in the locator.
10. Partial Link Text Locator
Partial Link Text is used when you want to identify a link using only part of its visible text.
HTML:
<a href="/products">View All Products</a>
Java:
driver.findElement(By.partialLinkText("Products")).click();
This can be useful when the complete link text is long or contains dynamic portions.
11. CSS Selector
A CSS Selector is a powerful locator strategy based on CSS selector syntax.
Java syntax:
driver.findElement(By.cssSelector("selector"));
CSS Selector by ID
driver.findElement(By.cssSelector("#username"));
CSS Selector by Class
driver.findElement(By.cssSelector(".login-button")).click();
CSS Selector by Attribute
driver.findElement(By.cssSelector("input[name='username']"));
CSS Selector by Tag and Attribute
driver.findElement(By.cssSelector("input[type='email']"));
CSS Selector with Multiple Classes
driver.findElement(By.cssSelector("button.btn.login-button"));
CSS Selector with Child Relationship
driver.findElement(By.cssSelector("div.login-form input"));
12. XPath Locator
XPath is a powerful locator strategy used to locate elements in the HTML DOM using path-based expressions and conditions.
Java syntax:
driver.findElement(By.xpath("xpathExpression"));
Basic XPath
driver.findElement(By.xpath("//input[@id='username']"));
XPath by Attribute
driver.findElement(By.xpath("//input[@name='email']"));
XPath by Text
driver.findElement(By.xpath("//button[text()='Login']")).click();
XPath with Multiple Attributes
driver.findElement(By.xpath("//input[@type='text' and @name='username']"));
XPath Using Contains
driver.findElement(By.xpath("//button[contains(@class,'login')]")).click();
XPath Using Starts-With
driver.findElement(By.xpath("//input[starts-with(@id,'user')]"));
XPath Using normalize-space()
driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();
13. Absolute XPath
An absolute XPath starts from the root of the HTML document and describes the complete path to an element.
/html/body/div/div/form/input
Example:
driver.findElement(By.xpath("/html/body/div/form/input[1]"));
Absolute XPath can become fragile when the HTML structure changes.
14. Relative XPath
A relative XPath starts from a relevant element rather than specifying the complete HTML hierarchy.
driver.findElement(By.xpath("//input[@id='username']"));
Relative XPath is generally easier to maintain than a long absolute XPath.
15. XPath Axes
XPath axes allow Selenium testers to navigate relationships between elements in the DOM.
| Axis | Purpose |
| parent | Selects the parent element |
| child | Selects child elements |
| ancestor | Selects ancestor elements |
| descendant | Selects descendant elements |
| following-sibling | Selects following sibling elements |
| preceding-sibling | Selects preceding sibling elements |
| following | Selects elements appearing later in the document |
| preceding | Selects elements appearing earlier in the document |
Parent Example
driver.findElement(By.xpath("//input[@id='username']/parent::*"));
Ancestor Example
driver.findElement(By.xpath("//input[@id='username']/ancestor::form"));
Following-Sibling Example
driver.findElement(By.xpath("//label[text()='Username']/following-sibling::input"));
16. findElement() Method
findElement() is used to locate a single web element.
WebElement element = driver.findElement(By.id("username"));
If Selenium cannot find a matching element, it throws a NoSuchElementException.
17. findElements() Method
findElements() is used to locate multiple matching elements.
List<WebElement> buttons = driver.findElements(By.tagName("button"));
It returns a list of WebElement objects.
Example
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println(link.getText());
}
18. Difference Between findElement() and findElements()
| Feature | findElement() | findElements() |
| Purpose | Finds one element | Finds multiple elements |
| Return Type | WebElement | List<WebElement> |
| No Match | Throws NoSuchElementException | Returns an empty list |
| Typical Usage | Username field, login button | Links, rows, checkboxes |
19. Locating Text Boxes
Text boxes can commonly be identified using ID, name, CSS selector, or XPath.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
Using XPath:
driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");
Using CSS:
driver.findElement(By.cssSelector("input[name='username']")).sendKeys("admin");
20. Locating Buttons
Buttons can be identified using ID, class, text, CSS selector, XPath, or other stable attributes.
driver.findElement(By.id("login")).click();
Using visible text:
driver.findElement(By.xpath("//button[text()='Login']")).click();
Using CSS:
driver.findElement(By.cssSelector("button.login-button")).click();
21. Locating Links
Links can be located using link text, partial link text, CSS selectors, or XPath.
driver.findElement(By.linkText("Home")).click();
Partial link text:
driver.findElement(By.partialLinkText("Home")).click();
22. Locating Checkboxes
Checkboxes can commonly be located using ID, name, CSS selector, or XPath.
WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
23. Locating Radio Buttons
WebElement maleRadio = driver.findElement(By.id("male"));
if (!maleRadio.isSelected()) {
maleRadio.click();
}
24. Locating Dropdown Elements
A dropdown can first be located using a normal locator and then handled using Selenium's Select class when the element is a standard HTML select element.
WebElement countryElement = driver.findElement(By.id("country"));
Example:
import org.openqa.selenium.support.ui.Select;
WebElement countryElement = driver.findElement(By.id("country"));
Select country = new Select(countryElement);
country.selectByVisibleText("India");
25. Locating Table Rows
Tables often contain multiple rows and cells. XPath and CSS selectors are useful for locating specific table data.
List<WebElement> rows =
driver.findElements(By.cssSelector("table tbody tr"));
for (WebElement row : rows) {
System.out.println(row.getText());
}
26. Locating Elements by Multiple Attributes
When one attribute is not unique, multiple attributes can be combined.
driver.findElement(
By.xpath("//input[@type='text' and @name='username']")
);
CSS example:
driver.findElement(
By.cssSelector("input[type='text'][name='username']")
);
27. Locating Dynamic Web Elements
Dynamic web elements are elements whose attributes or positions may change between page loads or user interactions.
For example:
<button id="login_827361">Login</button>
The numeric portion may change. Instead of relying on the complete ID, use a stable attribute or an XPath function.
driver.findElement(
By.xpath("//button[contains(@id,'login')]")
).click();
28. Using contains() in XPath
The contains() function is useful when only part of an attribute value is stable.
driver.findElement(
By.xpath("//input[contains(@id,'username')]")
);
It can also be used with class values:
driver.findElement(
By.xpath("//button[contains(@class,'submit')]")
);
29. Using starts-with() in XPath
The starts-with() function is useful when the beginning of an attribute value is stable.
driver.findElement(
By.xpath("//input[starts-with(@id,'user')]")
);
30. Using text() in XPath
The text() function can identify elements using their visible text.
driver.findElement(
By.xpath("//button[text()='Submit']")
).click();
For text containing extra spaces, normalize-space() can be useful.
driver.findElement(
By.xpath("//button[normalize-space()='Submit']")
).click();
31. Using OR and AND Conditions in XPath
AND
driver.findElement(
By.xpath("//input[@type='text' and @name='username']")
);
OR
driver.findElement(
By.xpath("//input[@id='username' or @name='username']")
);
32. CSS Attribute Selectors
CSS selectors support different attribute patterns.
| CSS Pattern | Meaning |
| [attribute='value'] | Exact attribute value |
| [attribute^='value'] | Attribute starts with value |
| [attribute$='value'] | Attribute ends with value |
| [attribute*='value'] | Attribute contains value |
Examples
By.cssSelector("input[name='username']");
By.cssSelector("input[id^='user']");
By.cssSelector("input[id$='name']");
By.cssSelector("input[id*='user']");
33. CSS Selector vs XPath
| Feature | CSS Selector | XPath |
| Syntax | CSS-based | XPath expression |
| Attribute Selection | Yes | Yes |
| Text Matching | Limited compared with XPath | Strong support |
| DOM Relationships | Good | Very powerful |
| Dynamic Elements | Useful | Very useful |
| Common Usage | Clean and flexible selectors | Complex element identification |
34. How to Choose a Good Locator
A good locator should be stable, unique, readable, and easy to maintain.
A practical preference order is:
- Unique and stable ID.
- Stable name attribute.
- Stable data-test or automation-specific attribute.
- Simple CSS selector.
- Reliable XPath.
- Link text or partial link text for appropriate links.
- Tag name when working with collections.
35. Stable Attributes for Automation
Modern applications often provide dedicated attributes for automation testing.
Example:
<button data-testid="login-button">Login</button>
CSS:
driver.findElement(
By.cssSelector("[data-testid='login-button']")
).click();
Such attributes can make locators more resistant to changes in presentation-related CSS classes.
36. Locator Priority Example
Suppose an element contains the following HTML:
<button id="loginBtn"
class="btn primary login"
data-testid="login-button">
Login
</button>
Possible locators include:
By.id("loginBtn");
By.cssSelector("[data-testid='login-button']");
By.cssSelector("button.login");
By.xpath("//button[@id='loginBtn']");
By.xpath("//button[normalize-space()='Login']");
The best choice depends on which attribute is stable and unique in the application.
37. Inspecting Elements in Browser Developer Tools
Before creating a locator, inspect the element using the browser's Developer Tools.
- Open the web application.
- Right-click the required element.
- Select Inspect.
- Find the corresponding HTML element.
- Look for stable attributes such as id, name, data-testid, or other unique attributes.
- Create and test the locator.
38. Example HTML Page
<form>
<input id="username" name="username" type="text">
<input id="password" name="password" type="password">
<button id="loginButton" class="login-btn">Login</button>
<a href="/forgot-password">Forgot Password?</a>
</form>
39. Locators for the Example Page
By.id("username");
By.name("username");
By.id("password");
By.name("password");
By.id("loginButton");
By.className("login-btn");
By.linkText("Forgot Password?");
By.partialLinkText("Forgot");
40. Complete Locator Example in Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebElement username =
driver.findElement(By.id("username"));
WebElement password =
driver.findElement(By.name("password"));
WebElement loginButton =
driver.findElement(By.id("loginButton"));
username.sendKeys("admin");
password.sendKeys("Password123");
loginButton.click();
} finally {
driver.quit();
}
}
}
41. Using Locators with WebElement
Once an element is located, the returned WebElement can be used to perform actions.
WebElement username =
driver.findElement(By.id("username"));
username.clear();
username.sendKeys("admin");
String value = username.getAttribute("value");
System.out.println(value);
42. Locators with Explicit Wait
For dynamic applications, locating an element immediately may fail if the element has not yet appeared or become visible.
Explicit waits can be combined with locators.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitWithLocator {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
username.sendKeys("admin");
} finally {
driver.quit();
}
}
}
43. Locators for Dynamic Elements
Dynamic applications frequently generate changing IDs, classes, or other attributes. In such cases, use stable portions of the DOM.
Example:
<input id="user_928372" name="username">
Instead of depending on the dynamic ID:
By.id("user_928372");
Use the stable name:
By.name("username");
Or use a partial XPath if appropriate:
By.xpath("//input[starts-with(@id,'user_')]");
44. Locators for Dynamic Classes
Some frameworks generate multiple CSS classes or change class names during application updates.
<button class="btn_87231 primary_9281">Submit</button>
If only part of the class is stable, a CSS attribute selector can be used:
By.cssSelector("button[class*='primary']");
Or XPath:
By.xpath("//button[contains(@class,'primary')]");
45. Avoiding Fragile Locators
Fragile locators are locators that frequently break when the application's HTML structure changes.
Avoid unnecessarily long XPath expressions such as:
/html/body/div[1]/div[2]/div[1]/form/div[2]/input
Prefer a shorter and meaningful locator:
By.id("username");
Or:
By.cssSelector("input[name='username']");
46. Common Locator Mistakes
- Using an incorrect attribute value.
- Using a dynamic ID as a permanent locator.
- Using an absolute XPath unnecessarily.
- Using multiple class names with By.className().
- Ignoring spaces in visible text.
- Creating a locator that matches multiple unintended elements.
- Using unstable CSS classes generated by frameworks.
- Not checking whether the element is inside an iframe.
- Not waiting for dynamic elements.
- Copying a very long XPath directly from Developer Tools without evaluating its stability.
47. Verifying Locator Uniqueness
A good locator should ideally identify the intended element uniquely.
For multiple matching elements:
List<WebElement> elements =
driver.findElements(By.cssSelector(".login-button"));
System.out.println("Matched elements: " + elements.size());
If multiple elements are returned unexpectedly, improve the locator.
48. Locator with Index
XPath can use indexing when multiple similar elements are present.
driver.findElement(
By.xpath("(//button[@type='button'])[1]")
).click();
Indexes should be used carefully because changes in page order can make them fragile.
49. Locating the Second Matching Element
driver.findElement(
By.xpath("(//input[@type='text'])[2]")
);
50. Locating Parent and Child Elements
XPath can be used when an element does not have a useful unique attribute but has a reliable relationship with another element.
driver.findElement(
By.xpath("//div[@class='login-form']//input[@name='username']")
);
51. Locating Sibling Elements
Suppose the HTML contains:
<label>Username</label>
<input type="text">
A relative XPath can locate the input:
driver.findElement(
By.xpath("//label[normalize-space()='Username']/following-sibling::input")
);
52. Locators in Page Object Model
In the Page Object Model (POM), locators are commonly stored as private fields inside page classes.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By username =
By.id("username");
private By password =
By.id("password");
private By loginButton =
By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(username).sendKeys(value);
}
public void enterPassword(String value) {
driver.findElement(password).sendKeys(value);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}
53. Advantages of Keeping Locators in Page Classes
- Improves code organization.
- Reduces duplication.
- Makes maintenance easier.
- Keeps test cases readable.
- Separates page structure from test logic.
- Makes locator changes easier to manage.
54. Locator Naming Conventions
Use meaningful variable names for locators.
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By loginButton = By.id("login");
private By forgotPasswordLink = By.linkText("Forgot Password?");
Avoid meaningless names such as:
private By element1 = By.id("username");
private By element2 = By.id("password");
55. Real-World Login Locator Example
WebElement username =
driver.findElement(By.id("username"));
WebElement password =
driver.findElement(By.id("password"));
WebElement login =
driver.findElement(By.cssSelector("button[type='submit']"));
username.sendKeys("testuser");
password.sendKeys("Password123");
login.click();
56. Real-World E-Commerce Locator Example
WebElement searchBox =
driver.findElement(By.id("search"));
searchBox.sendKeys("Laptop");
driver.findElement(
By.cssSelector("button.search-button")
).click();
driver.findElement(
By.xpath("//button[normalize-space()='Add to Cart']")
).click();
57. Real-World Registration Form Example
driver.findElement(By.id("firstName"))
.sendKeys("John");
driver.findElement(By.id("lastName"))
.sendKeys("Smith");
driver.findElement(By.name("email"))
.sendKeys("[email protected]");
driver.findElement(By.name("password"))
.sendKeys("Password123");
driver.findElement(
By.cssSelector("button[type='submit']")
).click();
58. Locators and WebDriver Flow
The basic Selenium interaction flow can be represented as:
Open Browser
|
v
Open Web Application
|
v
Inspect HTML Element
|
v
Choose Locator Strategy
|
v
Create By Locator
|
v
findElement()
|
v
Get WebElement
|
v
Perform Action
|
v
Validate Result
|
v
Continue Test
59. Locator Strategy Decision Flow
Does the element have a stable unique ID?
|
Yes
|
By.id()
No
|
v
Does it have a stable name?
|
Yes
|
By.name()
No
|
v
Is there a stable test attribute?
|
Yes
|
CSS Selector
No
|
v
Can CSS uniquely identify it?
|
Yes
|
CSS Selector
No
|
v
Can XPath reliably identify it?
|
Yes
|
XPath
No
|
v
Review the DOM and find a more stable attribute
60. Best Practices for Selenium Locators
- Prefer unique and stable attributes.
- Use ID when it is stable and unique.
- Use data-test or data-testid attributes when the application provides them for automation.
- Prefer short and readable CSS selectors.
- Use XPath for complex relationships and text-based identification.
- Avoid unnecessary absolute XPath.
- Avoid relying on dynamically generated values.
- Verify that the locator identifies the intended element.
- Use explicit waits for dynamic elements when synchronization is required.
- Keep locators inside Page Object classes for maintainable frameworks.
- Use meaningful locator variable names.
- Review locators whenever the application's UI structure changes.
61. Locator Comparison Table
| Locator | Example | Recommended Usage |
| ID | By.id("username") | Stable unique ID |
| Name | By.name("username") | Stable name attribute |
| Class Name | By.className("login") | Single stable class |
| Tag Name | By.tagName("button") | Collections of similar elements |
| Link Text | By.linkText("Login") | Exact link text |
| Partial Link Text | By.partialLinkText("Log") | Part of link text |
| CSS Selector | By.cssSelector("#username") | Clean and flexible selectors |
| XPath | By.xpath("//input[@id='username']") | Complex and relationship-based identification |
62. Locator vs WebElement
| Locator | WebElement |
| Describes how to find an element | Represents the located element |
| Created using By | Returned by findElement() |
| Example: By.id("username") | Example: WebElement username |
| Used to identify | Used to interact |
63. Common Locator Exceptions
NoSuchElementException
Occurs when Selenium cannot find the requested element.
InvalidSelectorException
Occurs when the CSS selector or XPath expression is invalid.
StaleElementReferenceException
Occurs when the previously located element is no longer attached to the current DOM.
ElementClickInterceptedException
Occurs when another element prevents Selenium from clicking the target element.
TimeoutException
Can occur when an explicit wait condition is not satisfied within the specified time.
64. Troubleshooting Locator Problems
| Problem | Possible Solution |
| Element not found | Verify locator and page state |
| Dynamic ID | Use a stable attribute or partial selector |
| Multiple elements found | Make the locator more specific |
| Click fails | Check visibility, overlays, and synchronization |
| Element becomes stale | Locate the element again after DOM refresh |
| XPath invalid | Check XPath syntax and quotation marks |
| CSS selector invalid | Check selector syntax |
| Element inside iframe | Switch to the required frame first |
65. Interview Questions on Selenium Locators
Q1. What is a locator in Selenium?
A locator is a mechanism used by Selenium WebDriver to identify a web element in the HTML DOM.
Q2. How many locator strategies are available in Selenium?
Selenium provides eight commonly used locator strategies: ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath.
Q3. What is the difference between findElement() and findElements()?
findElement() returns one WebElement and throws NoSuchElementException if no matching element is found. findElements() returns a list of matching WebElements and returns an empty list when there are no matches.
Q4. Which locator should be preferred?
A stable, unique locator should generally be preferred. If a unique and stable ID is available, it is often a straightforward choice. The best locator ultimately depends on the application's DOM and which attributes are stable.
Q5. What is XPath?
XPath is a query language used to navigate and identify elements in an XML or HTML DOM. Selenium supports XPath expressions for locating web elements.
Q6. What is the difference between absolute XPath and relative XPath?
Absolute XPath starts from the root of the document, while relative XPath starts from a specific element or condition. Relative XPath is generally easier to maintain.
Q7. What is a CSS Selector?
A CSS Selector is a selector syntax used to identify HTML elements based on IDs, classes, attributes, relationships, and other CSS patterns.
Q8. Can Selenium locate multiple elements?
Yes. The findElements() method can locate multiple matching elements and returns them as a List of WebElement objects.
Q9. How do you handle dynamic elements?
Use stable attributes, partial matching, CSS attribute selectors, XPath functions such as contains() and starts-with(), and appropriate synchronization techniques.
Q10. Why should absolute XPath generally be avoided?
Absolute XPath depends heavily on the complete DOM hierarchy. If the page structure changes, the XPath can easily become invalid.
Q11. Can we use multiple classes with By.className()?
No. By.className() expects a single class name. For multiple classes, CSS selectors are generally more appropriate.
Q12. What happens if findElement() cannot find an element?
Selenium throws a NoSuchElementException.
66. Quick Revision
| Concept | Key Point |
| Locator | Identifies a web element |
| By.id() | Uses the id attribute |
| By.name() | Uses the name attribute |
| By.className() | Uses one class name |
| By.tagName() | Uses HTML tag name |
| By.linkText() | Uses complete link text |
| By.partialLinkText() | Uses part of link text |
| By.cssSelector() | Uses CSS selector syntax |
| By.xpath() | Uses XPath expression |
| findElement() | Returns one WebElement |
| findElements() | Returns multiple WebElements |
| Dynamic Element | Use stable attributes and dynamic XPath/CSS techniques |
| Explicit Wait | Synchronizes with dynamic page elements |
| POM | Stores locators and page interactions in page classes |
67. Practical Project: Selenium Locator Practice
Build a small automation script that opens a web page and identifies different types of elements using different locator strategies.
Project Requirements
- Open the browser.
- Open a test web page.
- Locate a text box using ID.
- Locate another field using Name.
- Locate a button using CSS Selector.
- Locate a link using Link Text.
- Locate multiple links using Tag Name.
- Use XPath for a text-based element.
- Perform actions on the located elements.
- Close the browser using driver.quit().
68. Practical Locator Test Example
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorPractice {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebElement heading =
driver.findElement(By.tagName("h1"));
System.out.println("Heading: " + heading.getText());
List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println("Number of links: " + links.size());
for (WebElement link : links) {
System.out.println(link.getText());
}
} finally {
driver.quit();
}
}
}
69. Real-World Locator Workflow
Requirement
|
v
Identify Web Element
|
v
Inspect HTML
|
v
Find Stable Attribute
|
v
Choose Locator Strategy
|
+---- ID
|
+---- Name
|
+---- Class
|
+---- CSS
|
+---- XPath
|
v
Create By Locator
|
v
findElement()
|
v
Perform Action
|
v
Validate Result
|
v
Maintain Locator
70. Final Summary
Locators are a fundamental part of Selenium WebDriver automation. They allow Selenium to identify the exact web elements that need to be interacted with during automated testing.
In Java, Selenium provides eight primary locator strategies: ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. Each strategy has different use cases, and selecting a stable locator is important for reliable automation.
For dynamic applications, testers should prefer stable attributes and use techniques such as CSS attribute selectors, XPath functions, relative XPath, and explicit waits when appropriate. In professional automation frameworks, locators are commonly organized through the Page Object Model so that test scripts remain clean and maintainable.
Strong knowledge of locators is essential for creating reliable Selenium automation scripts, handling dynamic web applications, developing Page Object Model frameworks, and building real-world UI automation projects.
71. Course Resources
Learn more about Selenium Automation Testing:
Selenium Training
Register for a course demo:
Register for Course Demo